<template>
  <div class="user-management-page">
    <h2>用户管理</h2>
    <!-- 搜索和过滤区域 -->
    <div class="filters">
      <select v-model="selectedUserType" class="filter-select">
        <option value="">全部用户类型</option>
        <option value="0">客户</option>
        <option value="1">员工</option>
        <option value="2">管理员</option>
      </select>
      <button @click="openAddUserDialog" class="add-button">添加管理员</button>
    </div>

    <!-- 加载状态 -->
    <div v-if="userManagementStore.loading" class="loading-state">
      <div class="loading-spinner"></div>
      <span>加载中...</span>
    </div>

    <!-- 错误提示 -->
    <div v-else-if="userManagementStore.error" class="error-message">
      {{ userManagementStore.error }}
    </div>

    <!-- 用户列表 -->
    <div v-else class="user-table">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>用户名</th>
            <th>真实姓名</th>
            <th>用户类型</th>
            <th>公司</th>
            <th>手机号码</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in filteredUsers" :key="user.userId">
            <td>{{ user.userId }}</td>
            <td>{{ user.userName }}</td>
            <td>{{ user.realName }}</td>
            <td>{{ getUserTypeName(user.userType) }}</td>
            <td>{{ user.company || '无' }}</td>
            <td>{{ user.phone }}</td>
            <td>{{ getUserStatusName(user.status) }}</td>
            <td>
              <button @click="editUser(user)" class="edit-button">编辑</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 添加/编辑用户对话框 -->
    <div v-if="showDialog" class="dialog-overlay">
      <div class="dialog">
        <h3>{{ isEditing ? '编辑用户' : '添加管理员' }}</h3>
        <form @submit.prevent="handleSubmit">
          <div class="form-group">
            <label>用户名</label>
            <input v-model="currentUser.userName" required />
          </div>
          <div class="form-group">
            <label>真实姓名</label>
            <input v-model="currentUser.realName" required />
          </div>
          <div class="form-group">
            <label>手机号码</label>
            <input v-model="currentUser.phone" required pattern="^1[3-9]\d{9}$" />
          </div>
          <div class="form-group" v-if="isEditing">
            <label>用户类型</label>
            <select v-model="currentUser.userType" required>
              <option value="0">客户</option>
              <option value="1">员工</option>
              <option value="2">管理员</option>
            </select>
          </div>
          <div class="form-group" v-if="isEditing || currentUser.userType !== '2'">
            <label>公司</label>
            <input v-model="currentUser.company" :disabled="currentUser.userType === '1'" />
          </div>
          <div class="form-group">
            <label>状态</label>
            <select v-model="currentUser.status" required>
              <option value="0">冻结</option>
              <option value="1">正常</option>
              <option value="2">待审核</option>
            </select>
          </div>
          <div class="form-group" v-if="!isEditing">
            <label>密码</label>
            <input type="password" v-model="currentUser.password" required />
          </div>
          <div class="dialog-buttons">
            <button type="submit" :disabled="userManagementStore.loading">
              {{ userManagementStore.loading ? '处理中...' : (isEditing ? '保存' : '添加') }}
            </button>
            <button type="button" @click="closeDialog">取消</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useUserManagementStore } from '@/stores/userManagement';

// 状态变量
const userManagementStore = useUserManagementStore();
const selectedUserType = ref('');
const showDialog = ref(false);
const isEditing = ref(false);
const currentUser = ref({
  userName: '',
  realName: '',
  phone: '',
  userType: '2',
  company: '本公司',
  status: '1',
  password: ''
});

// 计算属性：过滤用户列表
const filteredUsers = computed(() => userManagementStore.filteredUsers(selectedUserType.value));

// 获取用户类型名称
const getUserTypeName = (type) => {
  const types = {
    0: '客户',
    1: '员工',
    2: '管理员'
  };
  return types[type] || '未知';
};

// 获取用户状态名称
const getUserStatusName = (status) => {
  const statuses = {
    0: '冻结',
    1: '正常',
    2: '待审核'
  };
  return statuses[status] || '未知';
};

// 打开添加用户对话框
const openAddUserDialog = () => {
  isEditing.value = false;
  currentUser.value = {
    userName: '',
    realName: '',
    phone: '',
    userType: '2',
    company: '本公司',
    status: '1',
    password: ''
  };
  showDialog.value = true;
};

// 打开编辑用户对话框
const editUser = (user) => {
  isEditing.value = true;
  currentUser.value = { ...user };
  showDialog.value = true;
};

// 关闭对话框
const closeDialog = () => {
  showDialog.value = false;
  currentUser.value = {
    userName: '',
    realName: '',
    phone: '',
    userType: '2',
    company: '本公司',
    status: '1',
    password: ''
  };
};

// 提交表单
const handleSubmit = async () => {
  try {
    let result;
    if (isEditing.value) {
      result = await userManagementStore.updateUser(currentUser.value.userId, currentUser.value);
    } else {
      result = await userManagementStore.addUser(currentUser.value);
    }

    if (result.success) {
      alert(isEditing.value ? '更新成功' : '添加成功');
      closeDialog();
    } else {
      alert(result.message || (isEditing.value ? '更新失败' : '添加失败'));
    }
  } catch (error) {
    alert((isEditing.value ? '更新' : '添加') + '失败：' + error.message);
  }
};

// 页面加载时获取用户列表
onMounted(() => {
  userManagementStore.loadUsers();
});
</script>

<style scoped>
.user-management-page {
  padding: 2rem;
}

.filters {
  margin-bottom: 1rem;
  display: flex;
  gap: 1rem;
}

.filter-select {
  padding: 0.5rem;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.add-button {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
}

.user-table {
  width: 100%;
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 1rem;
}

th, td {
  border: 1px solid #ddd;
  padding: 0.75rem;
  text-align: left;
}

th {
  background-color: #f5f5f5;
}

.edit-button {
  padding: 0.25rem 0.5rem;
  margin: 0 0.25rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  background-color: #2196F3;
  color: white;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog {
  background: white;
  padding: 2rem;
  border-radius: 8px;
  width: 100%;
  max-width: 500px;
}

.form-group {
  margin-bottom: 1rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.dialog-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1rem;
}

.dialog-buttons button {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.dialog-buttons button[type="submit"] {
  background-color: #4CAF50;
  color: white;
}

.dialog-buttons button[type="button"] {
  background-color: #9e9e9e;
  color: white;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 2rem;
  gap: 1rem;
}

.loading-spinner {
  width: 24px;
  height: 24px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.error-message {
  color: #f44336;
  text-align: center;
  padding: 1rem;
  background-color: #ffebee;
  border-radius: 4px;
  margin: 1rem 0;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>